package com.markerhub.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.dto.PassDto;
import com.markerhub.common.lang.Const;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.SysRole;
import com.markerhub.entity.SysUser;
import com.markerhub.entity.SysUserRole;
import com.markerhub.service.SysUserService;
import com.markerhub.utils.CSVUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.apache.tomcat.util.codec.binary.StringUtils.newStringUtf8;

@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

	@Autowired
	BCryptPasswordEncoder passwordEncoder;

	@Autowired
	SysUserService sysUserService;

	@PostMapping("/info")//通过用户名获取单个用户信息
	public Result info(@Validated @RequestBody SysUser sysUser) {

		SysUser sys = sysUserService.getByUsername(sysUser.getUsername());
		sys.setMajorName(sysMajorService.getMajorNameById(sys.getMajor()));
		sys.setCollegeName(sysCollegeService.getCollegeNameById(sys.getCollege()));
		return Result.succ(sys);
	}

	@GetMapping("/currentInfo")//获取当前登录的用户的信息
	public Result currentInfo(Principal principal) {

		SysUser sys = sysUserService.getByUsername(principal.getName());
		sys.setMajorName(sysMajorService.getMajorNameById(sys.getMajor()));
		sys.setCollegeName(sysCollegeService.getCollegeNameById(sys.getCollege()));
		return Result.succ(sys);
	}

	@GetMapping("/teacherList")//获取所有教师的信息
	public Result teacherList() {

		List<SysUser> sys = sysUserService.list(new QueryWrapper<SysUser>().eq("user_role","教师")
				.eq("statu","在读/在职"));

		return Result.succ(sys);
	}


	@GetMapping("/list")//获取用户列表
	public Result list(String username) {

		List<SysUser> pageData = sysUserService.list(new QueryWrapper<SysUser>()
				.like(StrUtil.isNotBlank(username), "username", username));
		pageData.forEach(u->
		{
			u.setCollegeName(sysCollegeService.getCollegeNameById(u.getCollege()));
			u.setMajorName(sysMajorService.getMajorNameById(u.getMajor()));
		});
		return Result.succ(pageData);
	}


	@PostMapping("/save")//管理员录入学生信息
	public Result save(@Validated @RequestBody SysUser sysUser) {

		// 默认密码
		String password = passwordEncoder.encode(Const.defultPassword);
		sysUser.setPassword(password);

		// 默认头像
		sysUser.setAvatar(Const.DEFULT_AVATAR);

		SysUser sys=null;
		sys=sysUserService.getObject(sysUser.getIdentificationNumber());

		if(sys!=null){
			return Result.fail("身份证号已存在");
		}else{
			sysUserService.save(sysUser);
			return Result.succ(sysUser);
		}
	}

	@PostMapping ("/bat") //批量导入
	public  Result bat(HttpServletRequest request){
		SysUser sysUser=new SysUser();
		sysUser.setMajor(sysMajorService.getIdByMajor(request.getParameter("major")));
		sysUser.setUserRole(request.getParameter("userRole"));
		sysUser.setUsername(request.getParameter("username"));
		sysUser.setName(request.getParameter("name"));
		sysUser.setEmail(request.getParameter("email"));
		sysUser.setCollege(sysCollegeService.getIdByCollege(request.getParameter("college")));
		sysUser.setPhoneNumber(request.getParameter("phoneNumber"));
		sysUser.setIdentificationNumber(request.getParameter("identificationNumber"));
		String password = passwordEncoder.encode(Const.defultPassword);
		sysUser.setPassword(password);

		// 默认头像
		sysUser.setAvatar(Const.DEFULT_AVATAR);

		SysUser sys=null;
		sys=sysUserService.getObject(sysUser.getIdentificationNumber());

		if(sys!=null){
			return Result.fail("身份证号已存在");
		}else{
			sysUserService.save(sysUser);
			return Result.succ(sysUser);
		}

	}

//	@PostMapping ("/save/batch")//批量导入，表格导入  **
//	public Result saveBatch(HttpServletRequest request) throws Exception {
//		String filePath = request.getParameter("filePath");
//		List<String> dataList = CSVUtils.importCsv(new File(filePath));
//		if (dataList != null && !dataList.isEmpty()) {
//			for (int i = 1; i < dataList.size(); i++) {
//				String data = dataList.get(i);
//				String[] source = data.split(",");
//				if (source[0] != "") {
//					SysUser sysUser=new SysUser();
//					// 默认密码
//					String password = passwordEncoder.encode(Const.defultPassword);
//					sysUser.setPassword(password);
//					sysUser.setUserRole(source[0]);
//					sysUser.setPhoneNumber(source[1]);
//					sysUser.setIdentificationNumber(source[2]);
//					sysUser.setName(source[3]);
//					sysUser.setUsername(source[4]);
//					sysUser.setEmail(source[5]);
//					sysUser.setCollege(Long.valueOf(source[6]));
//					sysUser.setMajor(Long.valueOf(source[7]));
//					// 默认头像
//					sysUser.setAvatar(Const.DEFULT_AVATAR);
//					sysUserService.save(sysUser);
//				}
//			}
//			return Result.succ("导入成功！");
//
//		}
//		return Result.fail("导入失败...");
//	}


	@PostMapping("/update")//用户修改自己的信息
	public Result update(@Validated @RequestBody SysUser sysUser,Principal principal) {

				sysUser.setId(sysUserService.getByUsername(sysUser.getUsername()).getId());
				sysUserService.updateById(sysUser);
				return Result.succ(sysUser);

	}

	@PostMapping("/update/admin")//管理员修改用户信息
	public Result updateAdmin(@Validated @RequestBody SysUser sysUser) {

		sysUser.setId(sysUserService.getByUsername(sysUser.getUsername()).getId());
		sysUserService.updateById(sysUser);
		return Result.succ(sysUser);

	}

	@PostMapping("/updatePass")//修改个人密码
	public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {

		SysUser sysUser = sysUserService.getByUsername(principal.getName());

		boolean matches = passwordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
		if (!matches) {
			return Result.fail("旧密码不正确");
		}

		sysUser.setPassword(passwordEncoder.encode(passDto.getPassword()));


		sysUserService.updateById(sysUser);
		return Result.succ("");
	}
}
